<?php
declare (strict_types = 1);

namespace app\index\model;

use app\common\model\message\Comment as CommentModel;
use app\common\utils\facade\AideUtil;
use think\Exception;

/**
 * @mixin think\Model
 */
class Comment extends CommentModel
{
    const LIMIT_KEY = 'comment_limit';
    const LIMIT_TIME = 300;//5分钟
    const LIMIT_NUM = 3; //单位时间内只允许评论3次

    const PAGE_LIMIT_NUM = 2;

    const REPLIES_LIMIT = 10;//一个评论最多可回复10次

    //检测速率(允许评论 返回true 不允许返回false)
    public function checkLimit(){
        $ret = AideUtil::setLimit(static::LIMIT_KEY, static::LIMIT_NUM, static::LIMIT_TIME);
        //如果超速 抛出异常
        if ( !$ret ) throw new Exception('评论太多,休息一下,');
        return $this;
    }

    //获取查询构造器
    public static function getQuery(array $where){
        return static::where($where);
    }

    //获取指定文章评论总数
    public static function getCount(int $article_id){
        return static::getQuery([
            'article_id'=> $article_id,
            'parent_id' => 0
            ])->count();
    }

    //获取评论列表
    public static function getList($page=null, $limit=null, int $article_id){
        $ret = static::getQuery([
                'article_id'=>$article_id,
                'parent_id' => 0
            ])
            ->with(['user','replies'])
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => empty($limit) || $limit < 1 || $limit > 15 ? static::PAGE_LIMIT_NUM : $limit,
                'page'      => empty($page) || $page <= 0 ? 1 : $page,
            ])->each(function($item, $key){
                $item->authorUrl = (string) url('user/read',['id'=>$item->user_id]);
                $item->absoluteTime = absoluteTime($item->create_time);
                $item->owner = $item->user_id  == app()->user->getId();
                foreach ($item->replies as $k => &$v){
                    $v['absoluteTime'] = absoluteTime($item->create_time);
                    $v['owner'] = $v['user_id'] == app()->user->getId();
                }

            })->toArray();

        return $ret;

    }
}
